﻿using System;
using System.Collections.ObjectModel;
using GalaSoft.MvvmLight;
using mal.WP7.Framework.Messages;
using mal.WP7.GoogleAnalytics.Business.Repository;

namespace mal.WP7.GoogleAnalytics.ViewModels
{
    public class ConfigurationViewModel : ViewModelBase
    {
        #region Fields
        private ReadOnlyCollection<Account> accounts;
        private Account selectedAccount;
        private bool hasAccount = false;
        #endregion

        #region Construction / Destruction
        public ConfigurationViewModel()
        {
            this.LoadAccounts();
        }
        #endregion

        #region enum, struct, class

        #endregion

        #region Properties
        public ReadOnlyCollection<Account> Accounts
        {
            get
            {
                return this.accounts;
            }

            set
            {
                if (this.accounts != value)
                {
                    this.accounts = value;
                    RaisePropertyChanged("Accounts");

                    if (this.Accounts != null && this.Accounts.Count > 0)
                    {
                        this.HasAccount = true;
                    }
                    else
                    {
                        this.HasAccount = false;
                    }
                }
            }
        }

        public Account SelectedAccount
        {
            get
            {
                return this.selectedAccount;
            }

            set
            {
                if (this.selectedAccount != value)
                {
                    this.selectedAccount = value;
                    RaisePropertyChanged("SelectedAccount");
                }

                if (this.selectedAccount != null)
                {
                    this.EditItem();
                }
            }
        }

        public bool HasAccount
        {
            get
            {
                return this.hasAccount;
            }

            set
            {
                if (this.hasAccount != value)
                {
                    this.hasAccount = value;
                    RaisePropertyChanged("HasAccount");
                }
            }
        }
        #endregion

        #region Methods
        public void LoadAccounts()
        {
            this.SelectedAccount = null;
            this.Accounts = WebsiteRepository.Instance.Accounts;
        }

        public void AddAccount()
        {
            NavigateMessage.Send(new Uri("/EditAccountPage.xaml?login=", UriKind.Relative));
        }

        private void EditItem()
        {
            NavigateMessage.Send(new Uri(string.Format("/EditAccountPage.xaml?login={0}", this.SelectedAccount.Login), UriKind.Relative));
        }
        #endregion

        #region Events

        #endregion
    }
}
